<template>
  <div class="edu-page-warp select-tutor-stu">
    <el-card shadow="never" class="condition-card">
      <el-form v-model="queryForm" label-position="right" label-width="100px" label-suffix="：" @submit.native.prevent @keyup.enter.native="searchList">
        <el-row :gutter="20" type="flex" align="center" justify="space-between">
          <el-col :span="3">
            <span class="condition-title">{{$t("message.filterCondition")}}</span>
          </el-col>
          <el-col :span="8" v-if="title === $t('graduationDesign.tutorList')">
            <el-form-item :label="$t('graduationDesign.college')">
              <el-select v-model="queryForm.collegeId" filterable class="search-item" clearable :disabled="indexKey === 'SELECT_STU'">
                <el-option v-for="item in source.collegeOptions" :key="item.collegeId" :label="item.collegeIdI18n" :value="item.collegeId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="this.teacherStuInfo.isTeacher">
            <el-form-item :label="$t('graduationDesign.tutorName')">
              <el-input v-model="queryForm.teacherName" :placeholder="$t('graduationDesign.pleaseEnter')" class="search-item" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="!this.teacherStuInfo.isTeacher">
            <el-form-item :label="$t('graduationDesign.studentName')">
              <el-input v-model="queryForm.studentName" :placeholder="$t('graduationDesign.fuzzySearch')" class="search-item" clearable></el-input>
            </el-form-item>
          </el-col>
          <div class="block-btn">
            <el-button @click="reset">{{$t("message.reset")}}</el-button>
            <el-button @click="searchList" type="primary">{{ $t("message.filter") }}</el-button>
          </div>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never">
      <div class="edu-page-title">{{title}}</div>
      <!--导师 学生列表-->
      <el-transfer
        v-model="teacherStuInfo.rightCheckedList"
        filterable
        :data="teacherStuInfo.stuTeacherData"
        @change="handleCheckChange"
        :titles="innerTitles"
        :props="{ key: teacherStuInfo.value, label: teacherStuInfo.label}"/>
      <el-transfer
        v-if="indexKey === 'SELECT_TEACHER'"
        v-model="teacherStuInfo.rightCheckedOuterList"
        filterable
        :data="teacherStuInfo.stuTeacherOuterData"
        :titles="outerTitles"
        :props="{ key: teacherStuInfo.value, label: teacherStuInfo.label}"/>
      <div class="edu-opertion-bar bottom-line">
        <div class="float-right bottom-btn">
          <el-button @click="onCancel">{{$t('graduationDesign.cancel')}}</el-button>
          <el-button type="primary" @click="onSubmit">{{$t('graduationDesign.submit')}}</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script>
import API from "common/src/api/underGraduationDesign/assignReplyStudent";

export default {
  name: '',
  props: {
    teacherStuInfo: { // 导师 学生信息
      type: Object,
      default: {
        value: '',
        label: '',
        rightCheckedList: [],
        // 导师 学生列表数据源
        stuTeacherData: [],
        rightCheckedOuterList: [],
        stuTeacherOuterData: []
      }
    },
    indexKey: 'SELECT_TEACHER'
  },
  data() {
    return {
      api: API,
      queryForm: {
        collegeId: '',
        studentName: '',
        teacherName: ''
      },
      source: {
        collegeOptions: [],
        subjectOptions: []
      },
      stuTeacherData: [], // 老师学生数据源
      // currentTitles: [this.$t('graduationDesign.toBeSelectedTutor'), this.$t('graduationDesign.selectedTutor')],
      innerTitles: [],
      outerTitles: ['待选老师(校外)', '已选导师(校外)'],
      title: ""
    };
  },
  mounted() {
    this.getCollege();
    this.title = this.$t('graduationDesign.tutorList');
    this.innerTitles = this.indexKey === 'SELECT_TEACHER' ? ['待选老师(校内)', '已选导师(校内)'] : ['待选学生', '已选学生'];
  },
  methods: {
    // 查学院
    getCollege() {
      this.api.getCollege().then(res => {
        this.source.collegeOptions = res;
        this.queryForm.collegeId = this.teacherStuInfo.replyTeamForm.collegeId;
      });
    },
    // 获取当前选中的学院名称
    getCurrentSelectCollegeName () {
      const selectedCollege = this.source.collegeOptions.filter(item => item.collegeId === this.queryForm.collegeId);
      if (selectedCollege && selectedCollege.length) {
        return selectedCollege[0].collegeIdI18n
      }
      return '';
    },
    searchList() {
      const selectType = this.teacherStuInfo.selectType;
      let req = null;
      const params = {
        id: this.teacherStuInfo.replyTeamForm.id,
        collegeId: this.queryForm.collegeId,
        studentName: this.queryForm.studentName,
        teacherName: this.queryForm.teacherName,
        graduationYear: this.teacherStuInfo.replyTeamForm.graduationYear,
        subjectId: this.teacherStuInfo.replyTeamForm.subjectId,
        defenseStartTime: this.teacherStuInfo.replyTeamForm.defenseStartTime,
        collegeName: this.getCurrentSelectCollegeName()
      };
      if (selectType === 1) {
        req = this.api.getTeacher(params);
      } else if (selectType === 2) {
        req = this.api.getStudent(params);
      } else {
        req = this.api.getForeignStudent(params);
      }
      req.then(res => {
        const data = res.data;
        if (this.teacherStuInfo.isTeacher) {
          const checked =
            this.teacherStuInfo.stuTeacherData.filter(item => this.teacherStuInfo.rightCheckedList.includes(item.teacherId));
          this.teacherStuInfo.stuTeacherData = this.mergeAndDuplicateRemoval(checked, data.innerTeachers, 'teacherId');
          const outerChecked =
            this.teacherStuInfo.stuTeacherOuterData.filter(item => this.teacherStuInfo.rightCheckedOuterList.includes(item.teacherId));
          this.teacherStuInfo.stuTeacherOuterData = this.mergeAndDuplicateRemoval(outerChecked, data.outerTeachers, 'teacherId');
          return;
        }
        const checked =
          this.teacherStuInfo.stuTeacherData.filter(item => this.teacherStuInfo.rightCheckedList.includes(item.studentId));
        this.teacherStuInfo.stuTeacherData = this.mergeAndDuplicateRemoval(checked, data, 'studentId');
      });
    },
    // 合并数组并根据key去重
    mergeAndDuplicateRemoval(array1, array2, key) {
      const result = [...(array1 || [])];
      (array2 || []).forEach(item => {
        if (!array1.some(obj => obj[key] === item[key])) {
          result.push(item);
        }
      });
      return result;
    },
    reset() {
      this.queryForm.collegeId = this.teacherStuInfo.replyTeamForm.collegeId;
      this.queryForm.teacherName = "";
      this.queryForm.studentName = "";
      this.teacherStuInfo.rightCheckedList = [];
      this.teacherStuInfo.rightCheckedOuterList = [];
      this.searchList();
    },
    // 格式化下拉框数据
    formatOptions() {
      const value = this.teacherStuInfo.value;
      const label = this.teacherStuInfo.label;
      const [ innerStuTeacherData, outerStuTeacherData ] = [[], []];
      (this.teacherStuInfo.stuTeacherData || []).forEach(item => {
        if ((this.teacherStuInfo.rightCheckedList || []).includes(item[value])) {
          const object = {};
          object[label] = item[label];
          object[value] = item[value];
          innerStuTeacherData.push(object);
        }
      });
      (this.teacherStuInfo.stuTeacherOuterData || []).forEach(item => {
        if ((this.teacherStuInfo.rightCheckedOuterList || []).includes(item[value])) {
          const object = {};
          object[label] = item[label];
          object[value] = item[value];
          outerStuTeacherData.push(object);
        }
      });
      return { innerStuTeacherData, outerStuTeacherData };
    },
    // 校验选择老师，学生列表
    validateTeacherStu() {
      const type = this.teacherStuInfo.columnType;
      const length = (this.teacherStuInfo.rightCheckedList || []).length + (this.teacherStuInfo.rightCheckedOuterList || []).length;
      // 只能有一个答辩组组长
      if (type === 'allDefenseGroupLeader' && length > 1) {
        this.$eduAlert("只能选择一个答辩组组长");
        return false;
      }
      // 答辩组成员会，不对小于5个
      if (type === 'allCommitteeMemberCodeList' && length < 5) {
        this.$eduAlert(this.$t('graduationDesign.replyCommitteeMemberValidateMsg'));
        return false;
      }
      // 答辩组老师，不能少于3个
      if (type === 'allTeacherCodeList' && length < 3) {
        this.$eduAlert(this.$t('graduationDesign.replyGroupTeacherValidateMsg'));
        return false;
      }
      return true;
    },
    onCancel() {
      this.$emit("teacher-stu-cancel");
    },
    // 选择老师、学生 提交
    onSubmit() {
      if (!this.validateTeacherStu()) {
        return false;
      }
      let options = this.formatOptions();

      this.$emit("teacher-stu-submit", this.teacherStuInfo, options);
    }
  }
}
</script>
<style lang="scss" scoped>
.select-tutor-stu {
    .condition-card {
        padding: 24px 0px;
        .condition-title {
            color: #2b3b4e;
            font-size: 18px;
            line-height: 24px;
            font-weight: bold;
        }
        .block-btn {
            text-align: right;
            padding-right: 0 !important;
            display: flex;
            flex-direction: row;
            justify-content: flex-end;
        }
    }
    .search-item {
        width: 100%;
    }
    .bottom-line {
        border-top: 1px solid #dcdfe6;
        margin-top: 20px;
        .bottom-btn {
            margin-top: 20px;
        }
    }
}
</style>
